package com.xueyi.rebar.mq.consumer;

import cn.iocoder.yudao.module.bpm.dal.dataobject.BpmProcessInstanceExtDO;
import com.xueyi.common.core.constant.basic.SecurityConstants;
import com.xueyi.common.core.context.SecurityContextHolder;
import com.xueyi.common.core.exception.ServiceException;
import com.xueyi.common.core.utils.JsonUtils;
import com.xueyi.common.core.utils.ServletUtils;
import com.xueyi.common.core.utils.StringUtils;
import com.xueyi.common.message.mq.callback.message.CallbackChannelMessage;
import com.xueyi.common.message.mq.pubsub.AbstractChannelMessageListener;
import com.xueyi.rebar.contant.FlowCodeEnum;
import com.xueyi.rebar.delivery.service.IRebarDistributionDeliveryOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
@Slf4j
public class CallbackChannelConsumer extends AbstractChannelMessageListener<CallbackChannelMessage> {

    @Resource
    private IRebarDistributionDeliveryOrderService rebarDistributionDeliveryOrderService;

    @Override
    public void onMessage(CallbackChannelMessage message) {
        String consumerMessage = message.getMessage();
        log.info("[rebar onMessage][收到 workflow callback消息]  伟大的超哥万岁！" + consumerMessage);
        System.out.println("[rebar onMessage][收到 workflow callback消息]  伟大的超哥万岁！" + consumerMessage);
        //deptService.initLocalCache();

        if(StringUtils.isNotEmpty(consumerMessage)){
            try{
                super.setMessageSourceHeaders(message);
                BpmProcessInstanceExtDO resultEvent = JsonUtils.parseObject(consumerMessage, BpmProcessInstanceExtDO.class);
                this.flowInstanceChangeEvent(resultEvent);
            }catch (Exception e){
                throw new ServiceException("回调消息解析异常："+message);
            }finally {
                SecurityContextHolder.remove();
            }
        }else{
            throw new ServiceException("回调消息解析异常："+message);
        }
    }

    public void flowInstanceChangeEvent(BpmProcessInstanceExtDO resultEvent) {
        String processDefinitionKey = resultEvent.getProcessDefinitionKey();
        FlowCodeEnum flowCodeEnum = FlowCodeEnum.getEnumByCode(processDefinitionKey);

        if (flowCodeEnum != null) {
            switch (flowCodeEnum) {
                case DELIVERY_ORDER:
                    //配送单审批
                    rebarDistributionDeliveryOrderService.approvalCallBack(resultEvent);
                    break;
            }
        }
    }
}
